import React, { useState, useEffect, useRef } from "react";
import styled from "styled-components";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { allUsersRoute, host } from "../utils/APIRoutes";
import Contacts from "../components/Contacts";
import Welcome from "../components/Welcome";
import ChatContainer from "./ChatContainer";
import { io } from "socket.io-client";

function Chat() {

    const [contacts, setContacts] = useState([]);
    const [currentUser, setCurrentUser] = useState(undefined);
    const navigate = useNavigate();
    const [currentChat, setCurrentChat] = useState(undefined);
    const socket = useRef();

    useEffect(() => {
        if (!localStorage.getItem("chat-app-user")) {
            navigate("/login");
        } else {
            const asyncData = async () => {
                const local = await JSON.parse(localStorage.getItem("chat-app-user"));
                setCurrentUser(local);
            }
            asyncData();
        }
    }, []);

    useEffect(() => {
        if (currentUser !== undefined) {
            if (currentUser.isAvatarImageSet) {
                const asyncData = async () => {
                    const { data } = await axios.get(`${allUsersRoute}/${currentUser._id}`);
                    setContacts(data);
                }
                asyncData();
            } else {
                navigate("/setAvatar")
            }
        }
    }, [currentUser]);

    useEffect(() => {
        if (currentUser !== undefined) {
            socket.current = io(host);
            socket.current.emit("add-user", currentUser._id);
        }
    }, [currentUser]);

    const handleChatChange = chat => {
        setCurrentChat(chat);
    }

    return (
        <Container>
            <div className="container">
                <Contacts
                    contacts={contacts}
                    currentUser={currentUser}
                    chatChange={handleChatChange}>
                </Contacts>
                {currentChat === undefined ? <Welcome currentUser={currentUser}></Welcome>
                    :
                    socket !== undefined && <ChatContainer currentChat={currentChat} currentUser={currentUser} socket={socket}></ChatContainer>}
            </div>
        </Container>
    )
}

const Container = styled.div`
    width: 100vw;
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 1rem;
    background-color: #131324;

    .container {
        width: 85vw;
        height: 85vh;
        background-color: #00000076;
        display: grid;
        grid-template-columns: 25% 75%;
        @media screen and (min-width: 720px) and (max-width: 1080px){
            grid-template-columns: 35% 65%;
        }
    }
`;

export default Chat;
